package com.thon.controller.rest;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.thon.dao.util.Page;
import com.thon.entity.project.Project;
import com.thon.entity.project.ProjectCategory;
import com.thon.entity.project.ProjectContributionView;
import com.thon.entity.project.ProjectStatistic;
import com.thon.service.project.ProjectCategoryService;
import com.thon.service.project.ProjectService;
import com.thon.service.project.ProjectStatisticService;

/**
 * @file ProjectRestController.java
 * @author Zemo
 * @mail zemochen@gmail.com
 * @data 2013年11月6日 上午11:59:14
 * @description: 项目信息接口
 */
@Controller


@RequestMapping(value = "/api")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class ProjectRestController {

	private static final Log log = LogFactory.getLog(ProjectRestController.class);

	@Autowired
	private ProjectService projectService;
	@Autowired
	private ProjectCategoryService projectCategoryService;
	@Autowired
	private ProjectStatisticService projectStatisticService;

	// 添加项目
	@RequestMapping(value = "/project/add", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> addProject(@RequestBody Project project) {

		//log.debug(">>>>>"+project.getId());	
		
		if(project.getId() == null){
			project.setStatus(0);
			project.setFundCurrent(0);
			project.setProductAmount(0);
			project.setSupportCount(0);
			project.setCommentCount(0);
			project.setAttentionCount(0);
			project.setRecommendCount(0);
			project.setShareCount(0);
			project.setViewCount(0);
			project.setRemainingDay(0);
			project.setFundTarget(0);
			project.setValidDays(0);
			projectService.addProject(project);
		
		}else{
			projectService.updateProject(project);			
		}		
		return new ResponseEntity(project, HttpStatus.CREATED);
	}

	//更改项目status
	@RequestMapping(value = "/project/submit",method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> submitProject(@RequestBody Project project,Model model){
		
		Project oldProject = new Project();
		oldProject = projectService.getProject(-1, project.getId());
		oldProject.setStatus(project.getStatus());
		projectService.updateProject(oldProject);
		model.addAttribute("project", oldProject);
		return new ResponseEntity(model,HttpStatus.OK);
	}
	// 根据project id 获取project详情
	@RequestMapping(value = "/project", method = RequestMethod.GET)
	public ResponseEntity<Project> getProject(@RequestParam(value = "pid",required = true) int projectId,
			@RequestParam(value = "uid",defaultValue="-1") int userId,
			Model model) {
		
		Project project = projectService.getProject(userId,projectId);
	//	Date endDate=(Date)project.getCreatedDate().clone();
	//	endDate.setDate(project.getCreatedDate().getDate()+project.getValidDays());
	//	SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
	//	model.addAttribute("endDate", df.format(endDate));
		model.addAttribute("project", project);	
		//Integer startNum=project.getInstitution().getProjects().size();
		//model.addAttribute("startNum",startNum);
		return new ResponseEntity(model, HttpStatus.OK);
	}

	//分页获取全部Project（根据角色获取status>?的项目）
	@RequestMapping(value = "/project/list/all")
	public ResponseEntity<HttpEntity> listAllProjects(
			@RequestParam(value = "status", defaultValue="-1") int status,
			@RequestParam(value = "uid",defaultValue="-1") int userId,
			@RequestParam(value = "p", defaultValue = "1") int pageNo,
			@RequestParam(value = "s", defaultValue = "4") int pageSize,
			@RequestParam(value = "qs", defaultValue = "") String queryStr){
		
		Page<Project> page = new Page<Project>();
		page = projectService.findAllProject(status,userId,pageNo, pageSize,queryStr);
		return new ResponseEntity(page, HttpStatus.OK);
	}
	// 根据状态(status)分页获取project
	@RequestMapping(value = "/project/list", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> listProject(
			@RequestParam(value = "status", required = true) int status,
			@RequestParam(value = "uid",defaultValue = "-1") int userId,
			@RequestParam(value = "p", defaultValue = "1") int pageNo,
			@RequestParam(value = "s", defaultValue = "4") int pageSize,
			Model model) {

		Page<Project> projcets = projectService.findProjects(userId,status, pageNo,pageSize);
		return new ResponseEntity(projcets, HttpStatus.OK);
	}
	
	//根据标签获取projects
	@RequestMapping(value = "/project/tags",method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> listProjectByTags(
			@RequestParam(value = "tags",required = true)String tags,
			@RequestParam(value = "uid",defaultValue = "-1") int userId,
			@RequestParam(value = "p",defaultValue = "1")int pageNo,
			@RequestParam(value = "s",defaultValue = "4")int pageSize){
		
		Page<Project> page = new Page<Project>();
		page = projectService.findProjectByTags(pageNo, pageSize, tags, userId);
		return new ResponseEntity(page,HttpStatus.OK);
	}
	
	/**
	 * 根据userId,action获取指定项目
	 * 
	 * @param userId
	 * @param action
	 *            : start 发起的项目 shares分享的项目 supports支持的项目 attentions关注的项目
	 *            recommends 推荐的项目
	 * @param pageNo
	 * @param pageSize
	 * @return page
	 */
	@RequestMapping(value = "/project/{action}", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> findProjectByAction(
			@RequestParam(value = "uid", required = true) int userId,
			@RequestParam(value="status",defaultValue="-1")int status,
			@PathVariable("action") String action,
			@RequestParam(value = "p", defaultValue = "1") int pageNo,
			@RequestParam(value = "s", defaultValue = "5") int pageSize) {

		if (action.equals("start")) {
			action = "start";
		} else {
			action = "ym_project_" + action;
		}
		Page<Project> page = projectService.findProjectByAction(userId, action,status,
				pageNo, pageSize);
		return new ResponseEntity(page, HttpStatus.OK);
	}

	// 获取项目自定义分类列表
	@RequestMapping(value = "/category")
	public ResponseEntity<HttpEntity> listProjectCategory(Model model) {
		
		List<ProjectCategory> projectCategories = projectCategoryService
				.listProjectCategories();
		model.addAttribute("projectCategories", projectCategories);
		return new ResponseEntity(model, HttpStatus.OK);
	}

	// 根据自定义分类的id获取项目
	@RequestMapping(value = "/category/project", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> findProjectByCategory(
			@RequestParam(value = "cid", required = true) int categoryId,
			@RequestParam(value = "status", defaultValue = "5") int status,
			@RequestParam(value = "p", defaultValue = "1") int pageNo,
			@RequestParam(value = "s", defaultValue = "10") int pageSize,
			@RequestParam(value="uid",defaultValue="-1") int userId) {

		Page<Project> page = projectService.findProjectByCategory(categoryId,pageNo, pageSize,userId,status);

		return new ResponseEntity(page, HttpStatus.OK);
	}

	// 根据项目id更新项目信息
	@RequestMapping(value = "/project/update", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> updateProject(
			@RequestBody Project project, Model model) {

		int id = project.getId();
		Project oldProject = projectService.getProject(-1,id);
		oldProject.setUserGender(project.getUserGender());
		oldProject.setUserPhone(project.getUserPhone());
		oldProject.setUserQQ(project.getUserQQ());
		oldProject.setUserRealName(project.getUserRealName());
		oldProject.setContect(project.getContect());
		projectService.updateProject(oldProject);	
		return new ResponseEntity(HttpStatus.OK);
	}
	
	/**
	* @Title: listProjectSort
	* @Description: TODO
	* @param by
	* 				latest 获取最新项目接口
	* 				finishes 获取即将完成项目接口
	* 				unrecommends 获取需要推荐项目接口
	* 				views 获取热门项目接口
	* @param pageNo 页码
	* @param pageSize 页大小
	* @return
	 */
	@RequestMapping(value = "/project/sort/{by}")
	public ResponseEntity<HttpEntity> listProjectSort(
			@PathVariable("by")String by,
			@RequestParam(value = "p",defaultValue = "1")int pageNo,
			@RequestParam(value = "s",defaultValue = "5")int pageSize,
			@RequestParam(value="uid",defaultValue = "-1") int userId,
			@RequestParam(value="status",defaultValue = "5") int status){
		Page<Project> page = projectService.findProjectSort(by,pageNo, pageSize,userId,status);
		return new ResponseEntity(page,HttpStatus.OK);
	}
	
	/**
	 * 统计项目
	 * @param by
	 * 				统计参数取值：1、comments 统计项目评论数
	 * 						 2、shares   统计项目分享数
	 * 						 3、supports 统计项目支持数
	 * 						 4、attentions 统计项目关注数
	 * @param projectId 项目Id
	 * @return List<ProjectStatistic> ProjectStatistic 包含date(日期，精确到天),count(Long)
	 */
	@RequestMapping(value="/project/statistic/{by}",method=RequestMethod.GET)
	public ResponseEntity<HttpEntity> statisticProject(
			@PathVariable(value="by") String by,
			@RequestParam(value="pid",required=true) Integer projectId){
		if(by.equals("comments")||by.equals("shares")||by.equals("supports")||by.equals("attentions")){
			List<ProjectStatistic> list =projectStatisticService.listStatisticList(projectId,by);
			return new ResponseEntity(list,HttpStatus.OK);
		}
		return new ResponseEntity(HttpStatus.BAD_REQUEST);				
	}
	
	/**
	 * 按日期获取指定项目当日最大交易额
	 * @param projectId 项目Id
	 * @param date 日期（Long型，默认为发出请求时的系统时间）
	 * @return ProjectStatistic
	 */
	@RequestMapping(value="/project/statistic/{pid}/topest",method=RequestMethod.GET)
	public ResponseEntity<HttpEntity> statisticTopestByDate(
			@PathVariable(value="pid") Integer projectId,
			@RequestParam(value="date",required=false) Long date){
		ProjectStatistic ps=new ProjectStatistic();
		Long topest=projectStatisticService.getTopestByDate(projectId,date);
		if(date!=null)
		ps.setDate(new Date(date));
		ps.setDate(new Date());
		ps.setCount(topest);		
		return new ResponseEntity(ps,HttpStatus.OK);		
	}
	
	@RequestMapping(value="/project/statistic/topcontribution/{by}",method=RequestMethod.GET)
	public ResponseEntity<HttpEntity> statisticTopSupportsByPro(
			@PathVariable(value="by") String by,
			@RequestParam(value="pid",required=true) Integer projectId
			,Model model){
		List<ProjectContributionView> pcvList=projectStatisticService.listTopContributionByPro(projectId,by);
		model.addAttribute("results", pcvList);
		return new ResponseEntity(model, HttpStatus.OK);		
	}
	
	/**
	 * @param regionId 区域id
	 * @param pageNo
	 * @param pageSize
	 * @return
	 * 根据城市id分页获取项目
	 */
	@RequestMapping(value = "/project/region")
	public ResponseEntity<HttpEntity> listProjectByRegion(
			@RequestParam(value = "rid")int regionId,
			@RequestParam(value = "status",defaultValue = "5")int status,
			@RequestParam(value = "p",defaultValue = "1")int pageNo,
			@RequestParam(value = "s",defaultValue = "4")int pageSize){
		
		Page<Project> page = new Page<Project>();
		page = projectService.findProjectByRegion(pageNo, pageSize, regionId,status);
		
		return new ResponseEntity(page,HttpStatus.OK);
	}
	//更新项目状态
	@RequestMapping(value="/project/update/status",method = {RequestMethod.GET,RequestMethod.POST})
	public ResponseEntity<?> updateProjectStatus(@RequestParam(value="projectId") int projectId,
												 @RequestParam(value="status") int status){
		Project project = projectService.getProject(projectId);
		project.setStatus(status);
		projectService.updateProject(project);
		return new ResponseEntity(true, HttpStatus.OK);
	}
	//通过categoryId筛选项目
	@RequestMapping(value="/project/list/by/category",method = RequestMethod.GET)
	public ResponseEntity<?> findProjectByCategory(@RequestParam(value="categoryId") int categoryId,
												   @RequestParam(value = "p",defaultValue = "1")int pageNo,
												   @RequestParam(value = "s",defaultValue = "4")int pageSize){
		Page<Project> page = new Page<Project>();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page.setTotalCount(page.getTotalCount());
		page = projectService.findProjectByCategory(page, categoryId);
		return new ResponseEntity(page, HttpStatus.OK);
	}
	//通过项目收益benefitId筛选项目
	@RequestMapping(value="/project/list/by/benefit",method = RequestMethod.GET)
	public ResponseEntity<?> findProjectBybenefit(@RequestParam(value="benefitId") int benefitId,
												  @RequestParam(value = "p",defaultValue = "1")int pageNo,
												  @RequestParam(value = "s",defaultValue = "4")int pageSize){
		Page<Project> page = new Page<Project>();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page = projectService.findProjectByBenefit(page, benefitId);
		return new ResponseEntity(page, HttpStatus.OK);
	}
	//通过开放平台openId筛选项目
	@RequestMapping(value = "/project/list/by/open",method = RequestMethod.GET)
	public ResponseEntity<?> findProjectByOpen(@RequestParam(value="openId") int openId,
											   @RequestParam(value = "p",defaultValue = "1")int pageNo,
											   @RequestParam(value = "s",defaultValue = "4")int pageSize){
		Page<Project> page = new Page<Project>();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page = projectService.findProjectByOpen(page, openId);
		return new ResponseEntity(page, HttpStatus.OK);
	}
	//根据项目id获得项目信息
	@RequestMapping(value="/project/listone",method = RequestMethod.GET)
	public ResponseEntity<?> listProjectById(@RequestParam(value="projectId") int projectId){
		Project project = projectService.getProject(projectId);
		return new ResponseEntity(project, HttpStatus.OK);
	}
}
